const db = wx.cloud.database()
import {
  baseActid,
  baseUrl
} from "../../utils/config"
import {
  http
} from "../../utils/http"
Page({
  data: {
    easyLogin: true,
    isShow: true
  },
  onLoad() {},
  async onShow() {
    const title = await db.collection('info').doc('28ee4e3e60b8a0381f7c1117027eac84').get()
    this.setData({
      className: title.data.className
    })
    if (!!wx.getStorageSync('isLogin')) {
      wx.redirectTo({
        url: `../xuan/xuan?title=${title.data.className}`
      })
    }
  },
  confirm() {
    this.setData({
      isShow: false,
      easyLogin: false
    })
  },
  getPhoneNumber(e) {
    wx.showLoading({
      title: '登录中...'
    })
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.cloud.callFunction({
        name: 'login',
        data: {
          id: e.detail.cloudID
        }
      }).then(res => {
        this.register(res.result.res.list[0].data.phoneNumber)
      }).catch(err => {
        wx.showToast({
          title: '授权失败',
          icon: 'none'
        })
        this.closeShade()
      })
    } else {
      wx.showToast({
        title: '授权失败',
        icon: 'none'
      })
      this.closeShade()
    }
  },
  register(phone) {
    http({
      url: `${baseUrl}getphonestatus?actid=${baseActid}`,
      data: {
        phone,
        sstime: new Date().getTime()
      }
    }).then(res => {
      const res_data = JSON.parse(res.data.substring(1, res.data.length - 1))
      if (res_data.status == 1) {
        wx.setStorageSync('isLogin', true)
        wx.setStorageSync('phone', phone)
        wx.redirectTo({
          url: `../xuan/xuan?title=${this.data.className}`
        })
        return
      }
      wx.showToast({
        title: "只有全款报班学员可以参加~",
        icon: "none"
      })
      this.closeShade()
    }).catch(err => {
      wx.showToast({
        title: '授权失败',
        icon: 'none'
      })
      this.closeShade()
    })
  },
  closeShade() {
    this.setData({
      isShow: !0,
      easyLogin: !0
    })
  }
})